﻿using System.Collections.Generic;
using OpenLS.Spreadsheet.Extensibility;

namespace OpenLS.Spreadsheet.StandardAddIn
{
    internal class RangeAndCriteria
    {
        private readonly Criteria _criteria;
        private readonly IRange _range;
        private CellRelativeAddress relativeAddress;
        private IRange _targetRange;

        public RangeAndCriteria(IWorkbook workbook, IRange range, object criteria, IRange valueRange)
        {
            _range = range;
            _criteria = new Criteria(workbook, criteria);
            this._targetRange = valueRange;
            relativeAddress = new CellRelativeAddress
                                  {
                                      Row = valueRange.RowIndex - range.RowIndex,
                                      Column = valueRange.ColumnIndex - range.ColumnIndex
                                  };
        }


        public IEnumerable<ICell> GetMaches()
        {
            foreach (ICell targetCell in _targetRange.GetNonEmptyCells())
            {
                var sourceCell = targetCell.ToRange()[-relativeAddress.Row, -relativeAddress.Column];
                if (_criteria.Matches(sourceCell.Value))
                {
                  //  ICell targetCell = cell.ToRange()[relativeAddress.Row, relativeAddress.Column]; // cell + a;
                    yield return targetCell;
                }
            }
           /* foreach (ICell cell in _range.GetNonEmptyCells())
            {
                if (_criteria.Matches(cell.Value))
                {
                    ICell targetCell = cell.ToRange()[relativeAddress.Row, relativeAddress.Column]; // cell + a;
                    yield return targetCell;
                }
            }*/
        }
        public IEnumerable<double> GetDoubleMatches()
        {
            IParameterConverter converter = CompositeArgumentConverter.ToDoubleConverter();

            foreach (var cell in GetMaches())
            {
                ICell targetCell = cell;
                object v = targetCell.Value;
                object res;
                double? dbl = null;
                if (v is double)
                    dbl = (double)v;
                var cd = new ConversionData(this._range.Worksheet.Workbook, _range.Worksheet, v, typeof(double));
                converter.Convert(cd);
                if (cd.Successful)
                {
                    if (cd.Error != null)
                        throw new ErrorException(cd.Error);
                    dbl = (double)cd.Result;
                }
                yield return  dbl.Value;
            }
        }
    }
}